// 知识库模块
document.addEventListener('DOMContentLoaded', function() {
	
    // DOM元素
    const knowledgePage = document.getElementById('knowledge-page');
    const knowledgeContainer = document.getElementById('knowledge-container');
    const categoryFilter = document.getElementById('category-filter');
    const searchInput = document.getElementById('search-input');
    const searchButton = document.getElementById('search-button');
    const loadingIndicator = document.getElementById('loading-indicator');
    const emptyState = document.getElementById('empty-state');
    const errorState = document.getElementById('error-state');
    const prevPageBtn = document.getElementById('prev-page');
    const nextPageBtn = document.getElementById('next-page');

    // 状态变量
    let currentCategory = 0; // 当前选中的分类ID，0表示全部分类
    let currentPage = 1;     // 当前页码
    let totalPages = 1;      // 总页数
    let searchKeyword = '';  // 当前搜索关键词
    const pageSize = 6;      // 每页数量

    // 初始化事件监听
    function initEventListeners() {
        // 监听知识库导航链接点击事件
        document.querySelectorAll('[data-page="knowledge"]').forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                loadKnowledgeData(0, 1, ''); // 加载全部分类的第一页数据
                showPage('knowledge'); // 显示知识库页面
            });
        });

        // 监听分类筛选下拉列表变化
        categoryFilter.addEventListener('change', function() {
            currentCategory = parseInt(this.value);
            loadKnowledgeData(currentCategory, 1, searchKeyword);
        });

        // 监听搜索按钮点击
        searchButton.addEventListener('click', function() {
            searchKeyword = searchInput.value.trim();
            loadKnowledgeData(currentCategory, 1, searchKeyword);
        });

        // 监听搜索输入框回车键
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchKeyword = this.value.trim();
                loadKnowledgeData(currentCategory, 1, searchKeyword);
            }
        });

        // 监听分页按钮点击
        prevPageBtn.addEventListener('click', function() {
            if (currentPage > 1) {
                loadKnowledgeData(currentCategory, currentPage - 1, searchKeyword);
            }
        });

        nextPageBtn.addEventListener('click', function() {
            if (currentPage < totalPages) {
                loadKnowledgeData(currentCategory, currentPage , searchKeyword);
            }
        });
    }

    // 加载知识数据
// 加载知识数据
function loadKnowledgeData(categoryId, page, keyword) {
    // 显示加载状态，隐藏其他状态
    showElement(loadingIndicator);
    hideElement(knowledgeContainer);
    hideElement(emptyState);
    hideElement(errorState);

    // 更新当前状态
    currentCategory = categoryId;
    currentPage = page;
    searchKeyword = keyword;

    // 构建API URL
    let apiUrl;
    if (categoryId === 0) {
        apiUrl = `http://localhost:8080/api/knowledge?page=${page}&pageSize=${pageSize}`;
    } else {
        apiUrl = `http://localhost:8080/api/knowledge/category/${categoryId}?page=${page}&pageSize=${pageSize}`;
    }

    // 添加搜索关键词
    if (keyword) {
        if (categoryId === 0) {
            apiUrl = `http://localhost:8080/api/knowledge/list?keywords=${encodeURIComponent(keyword)}&page=${page}&pageSize=${pageSize}`;
        } else {
            apiUrl = `http://localhost:8080/api/knowledge/category/${categoryId}/list?keywords=${encodeURIComponent(keyword)}&page=${page}&pageSize=${pageSize}`;
        }
		
    }

    // 调用API获取数据
    axios.get(apiUrl)
       .then(response => {
            const { data, total } = response.data;
            // 计算总页数
            totalPages = 2;//Math.ceil(total / pageSize);
            // 更新分页按钮状态
            updatePagination();
			currentPage = page; // ✅ 这句非常重要
            // 渲染知识列表
            if (data && data.length > 0) {
                renderKnowledgeList(data);
                showElement(knowledgeContainer);
            } else {
                showElement(emptyState);
            }
        })
       .catch(error => {
            console.error('加载知识失败:', error);
            showElement(errorState);
        })
       .finally(() => {
            hideElement(loadingIndicator);
        });
}

    // 渲染知识列表
    function renderKnowledgeList(knowledges) {
        knowledgeContainer.innerHTML = '';

        knowledges.forEach(knowledge => {
            const card = createKnowledgeCard(knowledge);
            knowledgeContainer.appendChild(card);
        });
    }

    // 创建知识卡片
    function createKnowledgeCard(knowledge) {
        // 定义分类样式映射
        const categoryStyles = {
            1: 'bg-green-100 text-green-700',    // 种植技术
            2: 'bg-orange-100 text-orange-700',  // 病虫害防治
            3: 'bg-blue-100 text-blue-700',      // 灌溉管理
            4: 'bg-purple-100 text-purple-700'   // 肥料管理
        };

        const card = document.createElement('div');
        card.className = 'bg-gray-50 rounded-lg p-4 card-hover transition-all duration-300 hover:shadow-md';
        // 获取分类样式
        const categoryStyle = categoryStyles[knowledge.categoryId] || 'bg-gray-100 text-gray-700';
        const categoryName = knowledge.categoryName || '未分类';

        // 格式化日期
        const formattedDate = formatDate(knowledge.createTime);

        card.innerHTML = `
          <div class="${categoryStyle} text-xs px-2 py-1 rounded mb-3 inline-block">${categoryName}</div>
          <h4 class="font-medium mb-2">${knowledge.title}</h4>
          <p class="text-gray-600 text-sm mb-3 line-clamp-2">
            ${knowledge.content.length > 100 ? knowledge.content.slice(0, 100) + '...' : knowledge.content || '暂无简介'}
          </p>
          <div class="flex items-center justify-between">
            <span class="text-xs text-gray-500">${formattedDate}</span>
            <button class="text-primary text-sm hover:underline" data-id="${knowledge.id}">查看详情</button>
          </div>
        `;

        // 添加点击事件
		card.querySelector('button').addEventListener('click', async function () {
		  const knowledgeId = this.getAttribute('data-id');
		
		  try {
		    const res = await axios.get(`http://localhost:8080/api/knowledge/${knowledgeId}`);
		    const knowledge = res.data.data;
		
		    // 页面切换
		    pages.forEach(p => p.classList.add('hidden'));
		    document.getElementById('knowledge-detail-page').classList.remove('hidden');
		    pageTitle.textContent = knowledge.title;
		
		    // 设置标题
		    const titleEl = document.getElementById('detail-title');
		    titleEl.textContent = knowledge.title;
		    titleEl.dataset.id = knowledge.id;
			// 直接进入编辑模式（替换详情内容为表单）
			startEditMode(knowledge);
		
		  } catch (err) {
		    console.error('获取详情失败:', err);
		    alert('获取知识详情失败');
		  }
		});


        return card;
    }

    // 更新分页控件状态
    function updatePagination() {
        // 更新页码显示
        prevPageBtn.parentElement.querySelector('span:not(.sr-only)')?.remove();
        nextPageBtn.parentElement.querySelector('span:not(.sr-only)')?.remove();
    
        const pageInfo = document.createElement('span');
        pageInfo.className = 'relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700';
        pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
    
        prevPageBtn.parentNode.insertBefore(pageInfo, nextPageBtn);
    
        // 禁用/启用上一页按钮
        if (currentPage === 1) {
            prevPageBtn.classList.add('opacity-50', 'cursor-not-allowed');
            prevPageBtn.removeEventListener('click', handlePrevPage);
        } else {
            prevPageBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            prevPageBtn.addEventListener('click', handlePrevPage);
        }
    
        // 禁用/启用下一页按钮
        if (currentPage === totalPages || totalPages === 0) {
            nextPageBtn.classList.add('opacity-50', 'cursor-not-allowed');
            nextPageBtn.removeEventListener('click', handleNextPage);
        } else {
            nextPageBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            nextPageBtn.addEventListener('click', handleNextPage);
        }
    }
    
    // 上一页点击处理
    function handlePrevPage() {
        loadKnowledgeData(currentCategory, currentPage - 1, searchKeyword);
    }
    
    // 下一页点击处理
    function handleNextPage() {
        loadKnowledgeData(currentCategory, currentPage + 1, searchKeyword);
    }

    // 格式化日期
    function formatDate(timestamp) {
        if (!timestamp) return '未知日期';
        const date = new Date(timestamp);
        return date.toISOString().split('T')[0]; // 返回 YYYY-MM-DD 格式
    }

    // 显示元素
    function showElement(element) {
        element.classList.remove('hidden');
    }

    // 隐藏元素
    function hideElement(element) {
        element.classList.add('hidden');
    }

    // 显示指定页面（用于多页面切换）
    function showPage(pageName) {
        document.querySelectorAll('.page').forEach(page => {
            page.classList.add('hidden');
        });

        const targetPage = document.getElementById(`${pageName}-page`);
        if (targetPage) {
            targetPage.classList.remove('hidden');
        }
    }

    // 初始化
    initEventListeners();
});

function startEditMode(knowledge) {
  const contentArea = document.getElementById('detail-content');
  const titleEl = document.getElementById('detail-title');
const id = knowledge.id;
  contentArea.innerHTML = `
    <div class="space-y-6 p-4 bg-white rounded shadow-md">
      <div>
        <label class="block text-sm font-semibold text-gray-700 mb-2">标题</label>
        <input
          id="edit-title"
          type="text"
          class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-blue-400"
          value="${knowledge.title}"
          placeholder="请输入标题"
        />
      </div>

      <div>
        <label class="block text-sm font-semibold text-gray-700 mb-2">分类</label>
        <input
          id="edit-category"
          type="text"
          class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-blue-400"
          value="${knowledge.categoryName || ''}"
          placeholder="请输入分类名称"
        />
      </div>

      <div>
        <label class="block text-sm font-semibold text-gray-700 mb-2">内容</label>
        <textarea
          id="edit-content"
          rows="10"
          class="w-full px-4 py-2 border border-gray-300 rounded-md resize-y focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-blue-400"
          placeholder="请输入内容"
        >${knowledge.content}</textarea>
      </div>

      <div class="flex justify-end space-x-4 pt-3">
        <button
          id="cancel-edit-btn"
          class="px-5 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition"
        >
          取消
        </button>
        <button
          id="save-edit-btn"
          class="px-5 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition shadow"
        >
          保存
        </button>
      </div>
    </div>
  `;

  document.getElementById('cancel-edit-btn').addEventListener('click', () => {
    location.reload();
  });

  document.getElementById('save-edit-btn').addEventListener('click', async () => {
    const newTitle = document.getElementById('edit-title').value.trim();
    const newCategory = document.getElementById('edit-category').value.trim();
    const newContent = document.getElementById('edit-content').value.trim();

    if (!newTitle || !newContent) {
      alert('标题和内容不能为空');
      return;
    }

    try {
	const res = await axios.put(`http://localhost:8080/api/knowledge/update/${id}`, {
	  title: newTitle,
	  content: newContent,
	  categoryName: newCategory
	});



      if (res.data.code === 200) {
        alert('修改成功');
        location.reload();
      } else {
        alert('保存失败：' + res.data.message);
      }
    } catch (err) {
      console.error('保存失败:', err);
      alert('请求失败，请稍后重试');
    }
  });
}
